/*******************************************************************************
  MPLAB Harmony Application Source File

  Company:
    Microchip Technology Inc.

  File Name:
    app.c

  Summary:
    This file contains the source code for the MPLAB Harmony application.

  Description:
    This file contains the source code for the MPLAB Harmony application.  It
    implements the logic of the application's state machine and it may call
    API routines of other MPLAB Harmony modules in the system, such as drivers,
    system services, and middleware.  However, it does not call any of the
    system interfaces (such as the "Initialize" and "Tasks" functions) of any of
    the modules in the system or make any assumptions about when those functions
    are called.  That is the responsibility of the configuration-specific system
    files.
 *******************************************************************************/

// DOM-IGNORE-BEGIN
/*******************************************************************************
* Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to comply with third party license terms applicable to your
* use of third party software (including open source software) that may
* accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
* EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
* INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
* WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
* BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
* FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
* ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*******************************************************************************/
// DOM-IGNORE-END

// *****************************************************************************
// *****************************************************************************
// Section: Included Files
// *****************************************************************************
// *****************************************************************************

#include <string.h>
#include "app.h"
#include "user.h"

#include "definitions.h"
#include "1lcd_lib_XC32.h"


char Buf[32]; 
char TransmitData[64];     //送信データバッファー

int ysNum1;
int myNum0,myNum1,myNum2,myNum3,myNum4,myNum5,myNum6,myNum7,myNum8,myNum9,myNum10;





int delay_Clock = 200000000;   //システムクロック:200MHz


void delay_us(volatile unsigned int usec)        //1μsec遅延
{
        volatile  int count;

        count = (int)(delay_Clock/20000000)*usec;


        do      //実測 at 200MH (Clock=200000000)
        {       //delay_us(1000):1000.4μsec  delay_us(100):100.6μsec  delay_us(10):10.5μsec  delay_us(1):1.5μsec
                asm("NOP"); asm("NOP"); asm("NOP"); asm("NOP"); asm("NOP");asm("NOP");
                asm("NOP"); asm("NOP"); asm("NOP"); asm("NOP"); asm("NOP"); asm("NOP");

                count--;
        }while(count != 0);


}



void delay_ms(volatile unsigned int msec)        //1msec遅延
{
        volatile unsigned int i;         //実測:at200MH (Clock=200000000)//delay_ms(1): 1.0006msec   delay_ms(100):100.04msec

        for(i=0; i<msec; i++)
        delay_us(1000);
}
void my_Initialize ( void )
{     
    lcd_init();				// LCD初期化
    lcd_cmd(0b00001100);    // カーソル:OFF  ブリンク:OFF    
        
    lcd_clear(); 
    
    lcd_cmd(0x80);          //1目の先頭へ
    sprintf(Buf,"UART Harmony        ");//
    lcd_str(Buf);                   //液晶表示
    

    lcd_cmd(0xC0);          //2行目の先頭へ
    sprintf(Buf," Harmony V3                        ");	//
    lcd_str(Buf);           // 開始メッセージ1行目表示
    
    
    delay_ms(2000);
    

    LED1_Clear();   // 
    
    
    
}





// *****************************************************************************
// *****************************************************************************
// Section: Global Data Definitions
// *****************************************************************************
// *****************************************************************************

// *****************************************************************************
/* Application Data

  Summary:
    Holds application data

  Description:
    This structure holds the application's data.

  Remarks:
    This structure should be initialized by the APP_Initialize function.

    Application strings and buffers are be defined outside this structure.
*/

APP_DATA appData;

static const char messageBuffer[] = "Hellow World !!\r\n";      //PIC32MZ立ち上がり時 送信文字列

// *****************************************************************************
// *****************************************************************************
// Section: Application Callback Functions
// *****************************************************************************
// *****************************************************************************

static void APP_USARTBufferEventHandler(
    DRV_USART_BUFFER_EVENT bufferEvent,
    DRV_USART_BUFFER_HANDLE bufferHandle,
    uintptr_t context
)
{
    switch(bufferEvent)
    {
        case DRV_USART_BUFFER_EVENT_COMPLETE:
            appData.transferStatus = true;  //送信状態:true
            break;

        case DRV_USART_BUFFER_EVENT_ERROR:
            appData.state = APP_STATE_ERROR;
            break;

        default:
            break;
    }
}

// *****************************************************************************
// *****************************************************************************
// Section: Application Local Functions
// *****************************************************************************
// *****************************************************************************


/* TODO:  Add any necessary local functions.
*/


// *****************************************************************************
// *****************************************************************************
// Section: Application Initialization and State Machine Functions
// *****************************************************************************
// *****************************************************************************

/*******************************************************************************
  Function:
    void APP_Initialize ( void )

  Remarks:
    See prototype in app.h.
 */

void APP_Initialize ( void )
{
    /* Place the App state machine in its initial state. */
    appData.state           = APP_STATE_INIT;
    appData.transferStatus  = false;
    appData.usartHandle     = DRV_HANDLE_INVALID;
    appData.bufferHandle    = DRV_USART_BUFFER_HANDLE_INVALID;
}


/******************************************************************************
  Function:
    void APP_Tasks ( void )

  Remarks:
    See prototype in app.h.
 */

void APP_Tasks ( void )
{
    ysNum1++;  
    
    /* Check the application's current state. */
    switch ( appData.state )
    {
 
        
        /* Application's initial state. */
        case APP_STATE_INIT:
            
            my_Initialize();    //ここにもってこないと動作がおかしい vs in APP_Initialize()
            
            myNum0++;
   

            appData.usartHandle = DRV_USART_Open(DRV_USART_INDEX_0, DRV_IO_INTENT_READWRITE);
                                    //UART6のドライバーインスタンスを定義し、ドライバーハンドルを生成
            if (appData.usartHandle != DRV_HANDLE_INVALID)      //ハンドルが正常に生成された場合
            {
                DRV_USART_BufferEventHandlerSet(appData.usartHandle, APP_USARTBufferEventHandler, 0);
                                                                //コールバック関数APP_USARTBufferEventHandlerを設定
                appData.state = APP_STATE_TRANSMIT_MESSAGE;
            }
            else    //ハンドルが正常に生成されなかった場合
            {
                appData.state = APP_STATE_ERROR;
            }
            break;

        case APP_STATE_TRANSMIT_MESSAGE:    //送信ステート
            myNum1++;

            DRV_USART_WriteBufferAdd(appData.usartHandle, (void*)messageBuffer, strlen(messageBuffer), &appData.bufferHandle);
                                                                            //バッファーに書き込み
            if (appData.bufferHandle != DRV_USART_BUFFER_HANDLE_INVALID)    //送信が成功してハンドルが正常に生成された場合
            {
                appData.state = APP_STATE_WAIT_MESSAGE_TRANSFER_COMPLETE;   //送信完了ステートへ
            }
            else
            {
                appData.state = APP_STATE_ERROR;
            }
            break;

        case APP_STATE_WAIT_MESSAGE_TRANSFER_COMPLETE:  //送信完了ステート
            myNum2++;
            if(appData.transferStatus == true)  //移転状態がtrueの場合
            {
                appData.transferStatus = false; //移転状態をfalseにセット
                appData.state = APP_STATE_RECEIVE_DATA;
            }
            break;

        case APP_STATE_RECEIVE_DATA:
            myNum3++;
             LED2_Set();
             delay_ms(1);
             LED2_Clear();
              delay_ms(1);
             
            DRV_USART_ReadBufferAdd(appData.usartHandle, appData.readBuffer, APP_DATA_SIZE, &appData.bufferHandle);//バッファを読み込み
            if (appData.bufferHandle != DRV_USART_BUFFER_HANDLE_INVALID)    //読み込みが成功した場合
            {
   
                
                appData.state = APP_STATE_WAIT_RECEIVE_COMPLETE;    //読み込み完了ステートへ
            }
            else
            {
                appData.state = APP_STATE_ERROR;
            }
            break;

        case APP_STATE_WAIT_RECEIVE_COMPLETE:   //読み込み完了ステート
            myNum4++;

            if(appData.transferStatus == true)  //移転状態がtrueの場合
            {
                appData.transferStatus = false; //移転状態をfalseにセット
                appData.state = APP_STATE_TRANSMIT_DATA;    //データ送信ステートへ
            }
            break;

        case APP_STATE_TRANSMIT_DATA:   //データ送信ステート
            myNum5++;

            /* Echo the received data back on the terminal */
            
            sprintf(TransmitData,"data=%s 0=%d 1=%d 2=%d 3=%d 4=%d 5=%d 6=%d 7=%d 8=%d 9=%d \r\n",
                    appData.readBuffer,myNum0,myNum1,myNum2,myNum3,myNum4,myNum5,myNum6,myNum7,myNum8,myNum9); //送信データの加工
            
            DRV_USART_WriteBufferAdd(appData.usartHandle, TransmitData, sizeof(TransmitData), &appData.bufferHandle);
            if (appData.bufferHandle != DRV_USART_BUFFER_HANDLE_INVALID)    //データの書き込みが成功した場合
            {
//    
//    
//    lcd_cmd(0x80);          //1目の先頭へ
//    sprintf(Buf,"Num3=%d                      ",myNum3);//
//    lcd_str(Buf);                   //液晶表示 
//    while(1);      
                
                

                
                appData.state = APP_STATE_WAIT_TRANSMIT_COMPLETE;   //送信完了ステートへ
            }
            else
            {
                appData.state = APP_STATE_ERROR;
            }
            break;

        case APP_STATE_WAIT_TRANSMIT_COMPLETE:  //送信完了ステート
            myNum6++;

            if(appData.transferStatus == true)  //移転状態がtrueの場合
            {
                appData.transferStatus = false; //移転状態をfalseにセット

                LED1_Toggle();   //
                   
//                
//    lcd_cmd(0x80);          //1目の先頭へ
//    sprintf(Buf,"%d,%d,%d,%d,                      ",myNum0,myNum1,myNum2,myNum3);//
//    lcd_str(Buf);                   //液晶表示 
//    
//    lcd_cmd(0xC0);          //2行目の先頭へ
//    sprintf(Buf,"%d,%d,%d,%d,%d,%d                        ",myNum4,myNum5,myNum6,myNum7,myNum8,myNum9);	//
//    lcd_str(Buf);           // 開始メッセージ1行目表示
//    while(1);


                appData.state = APP_STATE_RECEIVE_DATA; //データ受信ステートへ
            }
            break;

        case APP_STATE_ERROR:
            myNum7++;

            LED1_Clear();    //
          
            appData.state = APP_STATE_IDLE;
            break;

        case APP_STATE_IDLE:
            myNum8++;
             LED4_Set();    //点灯せず
            
        default:
            myNum9++;
            LED3_Set();
            break;
    }

    
    
    delay_ms(1);
    

}


/*******************************************************************************
 End of File
 */